package org.jeecg.modules.flow.callback.outbound.task;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.vo.OutBoundTaskSaveVO;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 出库任务保存 回调bean
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2023-09-26
 */
@RequiredArgsConstructor
@Component
public class OutBoundTaskSaveBean<T> extends BaseCustomBeanRun<T> {

    private final IWmsOutReceiptTaskService wmsOutReceiptTaskService;

    /**
     * 业务逻辑 保存或者更新出库任务
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        // 获取请求参数
        baseFlowDto.translateClass(OutBoundTaskSaveVO.class);
        OutBoundTaskSaveVO saveVO= (OutBoundTaskSaveVO)baseFlowDto.getData();
        WmsOutReceiptTask wmsOutReceiptTask = new WmsOutReceiptTask();
        BeanUtils.copyProperties(saveVO, wmsOutReceiptTask);
        String taskId;
        if(StrUtil.isEmpty(wmsOutReceiptTask.getId())){
            //保存出库任务
            taskId = wmsOutReceiptTaskService.saveMain(wmsOutReceiptTask, saveVO.getWmsOutReceiptTaskMaterialList());
        }else{
            taskId=wmsOutReceiptTask.getId();
            WmsOutReceiptTask wmsOutReceiptTaskEntity = wmsOutReceiptTaskService.getById(taskId);
            if (wmsOutReceiptTaskEntity == null) {
                throw new JeecgBootException("未找到对应数据");
            }
            wmsOutReceiptTaskService.updateMain(wmsOutReceiptTask, saveVO.getWmsOutReceiptTaskMaterialList());
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(taskId);
    }
}
